<?php
require CORE_PATH . 'Core/Vendor/Solr/Service.php';

/**
 * Class Core_Solr
 * @package Core
 */
class Core_Solr {
    // Singleton instances
    protected static $_instances;
    protected $host;
    protected $port;
    public $indexes;
    public $crt_index;

    /**
     * @param string $index_name
     * @return Core_Solr ininstance.
     */
    public static function getInstance($index_name) {
        if (empty(self::$_instances[$index_name])) {
            $core_solr = self::$_instances[$index_name] = new Core_Solr();
            $core_solr->crt_index = $core_solr->indexes[$index_name];
        }

        return self::$_instances[$index_name];
    }

    private function __construct($solr_config_name = 'default') {
        $config = Core_Config::get("solr.{$solr_config_name}");
        $this->indexes = $config['indexes'];
        $this->host = $config['host'];
        $this->port = $config['port'];
    }

    /**
     * @param $query
     * @param int $offset
     * @param int $limit
     * @param array $params
     * @return bool|mixed
     */
    public function search($query, $offset = 0, $limit = 10, $params = array()) {
        $solrServer = new Apache_Solr_Service($this->host, $this->port, '/solr/' . $this->crt_index);

        $response = $solrServer->search($query, $offset, $limit, $params);

        if ($response->getHttpStatus() == 200) {
            return $response->response;
        } else {
            return false;
        }
    }
    
    public function deleteById($id){
        $solrServer = new Apache_Solr_Service($this->host, $this->port, '/solr/' . $this->crt_index);
        $solrServer->deleteById($id);
        $solrServer->commit();
    }

    public static function escape($value) {
        return Apache_Solr_Service::escape($value);
    }

    public static function escapePhrase($value) {
        return Apache_Solr_Service::escapePhrase($value);
    }

}
